package com.wondream.myframework.app.common.excel.converter;

import com.google.common.collect.Lists;
import com.wondream.myframework.app.common.excel.CfssPoiImporter;
import com.wondream.myframework.app.common.excel.domain.CfssExcelData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.ParameterizedType;
import java.util.*;

/**
 * excel转换器
 */
@Slf4j
public class CfssExcelConverter implements ConditionalGenericConverter {

    @Autowired(required = false)
    private CustomExcelConverterExtend customExcelConverterExtend;

    /**
     * excel转换器满足规则
     */
    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return CfssExcelData.class.isAssignableFrom(targetType.getType()) &&
                MultipartFile.class.isAssignableFrom(sourceType.getType());
    }

    /**
     * excel转换器支持的入参和出参
     */
    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(MultipartFile.class, CfssExcelData.class));
    }

    /**
     * excel转换实现类
     */
    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        MultipartFile multipartFile = (MultipartFile) source;
        Map<Class, List> datas = null;
        try {
            ParameterizedType type = (ParameterizedType) targetType.getResolvableType().getType();
            Class clazz = (Class) type.getActualTypeArguments()[0];
            ArrayList<Class> entityClazz = Lists.newArrayList(clazz);
            List dataInfos = null;
            if (null != customExcelConverterExtend) {
                dataInfos = customExcelConverterExtend.transferMultipartToParam(multipartFile, targetType);
            } else {
                datas = CfssPoiImporter.importExcel(multipartFile.getInputStream(), entityClazz);
                dataInfos = datas.get(clazz);
            }
            CfssExcelData excelData = new CfssExcelData<>();
            excelData.setDatas(dataInfos);
            return excelData;
        } catch (Exception e) {
            log.error("CfssExcelConverter.convert转换异常:" + e.getMessage());
        }
        return null;
    }
}
